package listings.ui;

import java.io.FileReader;
import java.io.Reader;
import java.util.Map;

import listings.Listing;
import listings.Program;
import listings.Schedule;
import listings.Station;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Unmarshaller;

import ui.Command;
import ui.Dialog;
import util.UnexpectedException;

public class StationParser extends Command
{
	private Dialog dialog;

	@Override
	public boolean execute()
	{
		try
		{
			String fileName = dialog.ask("Data file? ", "data_files/gold_sample.xml");
			// Load Mapping
			Mapping mapping = new Mapping();
			mapping.loadMapping("src/mapping.xml");

			// Create a Reader to the file to unmarshal from
			Reader reader = new FileReader(fileName);

			// Create a new Unmarshaller
			Unmarshaller unmarshaller = new Unmarshaller(mapping);
//			unmarshaller.setIgnoreExtraElements(true);
			// Unmarshal the person object
			Listing listing = (Listing)unmarshaller.unmarshal(reader);
			Map<Long, String> lineup = listing.getLineup();
			for (Station station : listing.getStations())
			{
				String channel = lineup.get(station.getId());
				dialog.display(
						"Name: " + station.getName() + " Channel: " + channel);
			}
			dialog.display("Num schedules: " + listing.getSchedules().size());
			for (Schedule schedule : listing.getSchedules())
			{
				Program program = schedule.getProgram();
				if (program != null && program.getId().equals("EP0809550108"))
				{
					dialog.display(
							program.getTitle() +
							" on " + schedule.getStation().getName() +
							" at " + schedule.getTime() + 
							" for " + schedule.getDuration() +
							" Part " + schedule.getPartNumber() + 
							" of " + schedule.getTotalParts() +
							" (" + schedule.getTvRating() + ")");
				}
			}
		} catch (Exception e)
		{
			throw UnexpectedException.wrap(e);
		}
		
		return true;
	}

	/**
	 * @return the dialog
	 */
	public Dialog getDialog()
	{
		return dialog;
	}

	/**
	 * @param dialog the dialog to set
	 */
	public void setDialog(Dialog dialog)
	{
		this.dialog = dialog;
	}

}
